package org.ziegler.javabase.thread.single;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 单线程线程池，如果线程崩溃，会重启另外一个线程。
 * 保持单线程线程池总是有一个线程可以使用。
 *
 * @auther HanZhe
 * @date 2020/6/3 13:24
 */
public class SingleThreadTest {
    final ExecutorService exec = Executors.newSingleThreadExecutor();

    void execute(Runnable runnable) {
        exec.execute(runnable);
    }

    Future submit(Runnable runnable) {
        return exec.submit(runnable);
    }

    void shutdownGracefully() {
        exec.shutdown();
        try {
            exec.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SingleThreadTest st = new SingleThreadTest();
        st.execute(() -> {
            System.out.println("threadId:" + Thread.currentThread().getId());
            Integer n = null;
            System.out.println("n = " + n.toString());
        });

        st.execute(() -> {
            System.out.println("threadId:" + Thread.currentThread().getId());
            Integer n2 = null;
            int n = n2;
            System.out.println("n = " + n);
        });

        st.submit(() -> {
            System.out.println("threadId:" + Thread.currentThread().getId());
        });

        st.shutdownGracefully();

    }
}
